var getPostData = require('./common.js').getPostData;
var PublishProxy = require('../../../proxy/publish.js');
var EventProxy = require('eventproxy');
var messageBroker = require('../../../messageBroker.js');
var logger = require('log4js').getLogger();
var publish_to_store = require('./common.js').publish_to_store;
var upload = require('./common.js').upload;
var config = require('../../../config.json');
var fs = require('fs');
var path = require('path');
var zip = require('../../../common/zip');
var decompress = require('decompress');
var decompressUnzip = require('decompress-unzip');
var tools = require('../../../common/tools.js');

function publish(req, res) {
    var ep = new EventProxy();

    var body = req.body;
    var publishInfo = getPostData(body).publishInfo;
    var goodsInfo = getPostData(body).goodsInfo;
    //var task_id = uuid.v1();
    goodsInfo.type = body.productsInfo[0].type;
    ep.after("publish_created", 1, function () {
        publish_to_store(publish_info._id, goodsInfo, function () {
        upload_product_files(body, publish_info._id, "app_plugin");
        });
    });
    publishInfo.state = "publish_created";
    PublishProxy.addPublishInfo(publishInfo, function (err, data) {
        if (err) {
            logger.error(err);
            return res.format_json(null, 500, "商品发布任务发起失败：" + JSON.stringify(err));
        }
        publish_info = data;
        messageBroker.emit('publish_state_update', {body: {state: "publish_created"}, err: null});
        logger.info("发布任务发起成功：" + JSON.stringify(data));
        ep.emit("publish_created");
        return res.format_json({'msg': "商品发布任务发起成功!", 'task_id': JSON.parse(JSON.stringify(data))._id}, 200);
    });
}

function upload_product_files(body, publish_id) {
    var products = body.productsInfo;
    var targetPath;
    try {
        fs.accessSync(config.publish_temp, fs.R_OK);
    } catch (e) {
        fs.mkdirSync(config.publish_temp);
    }
    if (products.length > 0) {
        var sourceFiles = [];
        products.map(function (product) {
            try {
                fs.accessSync(product.file, fs.R_OK);
            } catch (e) {
                PublishProxy.updatePublishState(publish_id, "product_error", function () {
                    messageBroker.emit('publish_state_update', {body: {state: "product_error"}, err: null});
                    messageBroker.emit(publish_id, {task_id: publish_id, body: null, err: {msg: '商品上传失败'}});
                    logger.error(e);
                });
                return false;
            }
            sourceFiles.push(product.file);
        });
        targetPath = path.join(config.publish_temp, body.goodsName + '.zip');
        //sourceFiles 解压后重命名为商品名
        var product_path = path.resolve(sourceFiles[0], '..');
        var temp_dir = path.join(product_path,publish_id.toString());
        fs.mkdirSync(temp_dir);
            zip.unzip(sourceFiles[0], temp_dir, function (err, data) {
            if (err) {
                logger.error(err);
                return false;
            }
            //fs.unlinkSync(sourceFiles[0]);
            fs.readdir(temp_dir, function (err, arr) {
                fs.mkdirSync(path.join(temp_dir, 'nectar_plugin'));
                fs.renameSync(path.join(temp_dir, arr[0]), path.join(temp_dir, 'nectar_plugin',body.goodsName + "_" + body.version));
                zip.zip(path.join(temp_dir,'nectar_plugin'), path.join(temp_dir, 'nectar_plugin.zip'), function (err, data) {
                    if (err) {
                        return false;
                    } else {
                        tools.rmdirAllSync(path.join(temp_dir,'nectar_plugin'));
                        var sourceFiles = [path.join(temp_dir,'nectar_plugin.zip')];
                        zip.zipFiles(sourceFiles, targetPath, function (err, data) {
                            if (err) {
                                PublishProxy.updatePublishState(publish_id, "product_error", function () {
                                    messageBroker.emit('publish_state_update', {
                                        body: {state: "product_error"},
                                        err: null
                                    });
                                    messageBroker.emit(publish_id, {
                                        task_id: publish_id,
                                        body: null,
                                        err: {msg: '商品上传失败'}
                                    });
                                    logger.error(err);
                                });
                                return false;
                            }
                            try {
                                fs.accessSync(targetPath, fs.R_OK);
                            } catch (e) {
                                logger.error('压缩结果不存在:' + targetPath);
                            }
                            PublishProxy.updatePublishState(publish_id, "products_prepared", function () {
                                messageBroker.emit('publish_state_update', {
                                    body: {state: "products_prepared"},
                                    err: null
                                });
                                upload(body.goodsName, path.join(config.publish_temp, body.goodsName + '.zip'), "app_plugin", body.version, function (error, result) {
                                    if (error) {
                                        PublishProxy.updatePublishState(publish_id, "upload_failed", function () {
                                            messageBroker.emit('publish_state_update', {
                                                body: {state: "upload_failed"},
                                                err: null
                                            });
                                            messageBroker.emit(publish_id, {
                                                task_id: publish_id,
                                                body: null,
                                                err: {msg: '商品上传失败'}
                                            });
                                            logger.error(error);
                                        })
                                    }
                                    if (200 == result) {
                                        PublishProxy.updatePublishState(publish_id, "uploaded", function () {
                                            messageBroker.emit('publish_state_update', {
                                                body: {state: "uploaded"},
                                                err: null
                                            });
                                            messageBroker.emit(publish_id, {
                                                task_id: publish_id,
                                                body: {msg: '商品发布完成'},
                                                err: null
                                            });
                                            logger.info('文件上传成功');
                                        })
                                    }
                                })
                                }
                            );

                            }
                        );
                    }
                })
                ;
            });
        });
    } else {
        logger.error("商品中不包含任何产品！");
        PublishProxy.updatePublishState(publish_id, "product_error", function () {
            messageBroker.emit('publish_state_update', {body: {state: "product_error"}, err: null});
            messageBroker.emit(publish_id, {task_id: publish_id, body: null, err: {msg: '商品上传失败'}});
        });
    }
}
exports.upload_product_files = upload_product_files;
exports.publish = publish;